package com.shinowit.web.login;

import java.sql.Types;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.shinowit.model.Result;

@Controller
@RequestMapping(value="/login")
public class LoginController {

	@Resource
	private JdbcTemplate jt;
	
	private static final Logger logger=Logger.getLogger(LoginController.class);
	
	@RequestMapping(value={"/",""},method=RequestMethod.GET)
	public String openLoginPage(Model model){
		return "/login/login";
	}
	
	@RequestMapping("/validcode")
	public String validCode(){
		return "/login/validcode";
	}
	
	@RequestMapping(value="/",method=RequestMethod.POST)
	@ResponseBody
	public Result checkLogin(Model model,String username,String userpass,String validcode,HttpServletRequest request){
		Result result=new Result("服务器端错误!",false);
		
		try{
//			String server_side_valid_code=(String)request.getSession(true).getAttribute("rCode");
//			if ((null==validcode) || (validcode.trim().length()==0)){
//				result.setMsg("验证码输入错误!");
//				return result;
//			}
//			
//			if (null==server_side_valid_code){
//				return result;	
//			}
			
//			if (!server_side_valid_code.equals(validcode)){
//				result.setMsg("验证码输入错误!");
//				return result;
//			}
			
			int i=jt.queryForObject("select count(0) from sys_user where user_name=? and login_pass=?", new Object[]{username,userpass},new int[]{Types.VARCHAR,Types.VARCHAR},Integer.class); 
			
			if (i>0){
				//查询可以操作的系统功能模块
				

				
				request.getSession(true).setAttribute("current_user", username);
				result.setMsg("登陆成功!");
				result.setStatus(true);
			}else{
				result.setMsg("用户名或者密码输入有误!");
			}
		}catch(Exception e){
			logger.error(e.getMessage(),e);
		}
		return result;
	}
	
	@RequestMapping(value="/logout")
	public String logout(HttpSession session){
		session.invalidate();
		return "redirect:/login/";
	}
	
}
